<!--
@fucntion: 角色信息管理-面板
-->
<template>
<div class="components-system-role">
  <el-row style="height:100%;">
    <el-col style="height:100%;" :xs="24" :sm="24" :md="12" :lg="12">
      <table-panel :name="'角色信息'" :columns="roleColumns" :tableData="roleData" :height="665" :showRowNumber="true"
      :canCreate="authorities.create" :canEdit="authorities.edit" :canDelete="authorities.delete"
      :currentPage="roleCurrentPage" :totalNum="roleTotalNum" @page-change="onPageChange('role',$event)" :pageSize="pageSize"
      @table-searching="onSearching('role',$event)" @table-create="onCreate('role',$event)"
      @table-edit="onEdit('role', $event)" @table-delete="onDelete('role',$event)"
      @table-export="onExport('role',$event)" @current-change="onSelectionChange('role',$event)"></table-panel>
    </el-col>
    <el-col style="height:100%;" :xs="24" :sm="24" :md="12" :lg="12">
      <tree-panel ref="authorityTree" :panelTitle="'角色权限'" :hasToolbar="true" :expandAll="true"
      :treeData="authorityTree"
      @check-change="onCheckChange">
        <template slot="toolbar">
          <el-button style="margin:7px 15px;" size="mini" @click="onSave">保存权限分配</el-button>
        </template>
      </tree-panel>
    </el-col>
    <el-dialog title="角色信息" width="20%" :visible.sync="roleDlgVisible">
      <el-form ref="roleForm" :model="roleRecord" :rules="roleRules"
      label-position="right" label-width="80px" size="mini" status-icon>
        <el-form-item label="角色名称" prop="jsmc">
          <el-input v-model="roleRecord.jsmc"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="path">
          <el-input v-model="roleRecord.jsms"></el-input>
        </el-form-item>
        <el-checkbox v-model="roleRecord.sfqy" label="有效否" true-label="1" false-label="0">
        </el-checkbox>
        <el-row>
          <el-button @click="onConfirm('role', $event)" type="primary" size="mini">确定</el-button>
          <el-button @click="roleDlgVisible=false" size="mini">取消</el-button>
        </el-row>
      </el-form>
    </el-dialog>
  </el-row>
</div>
</template>
<script>
import TablePanel from "@/components/basic/TablePanel";
import TreePanel from "@/components/basic/TreePanel";
import {
  formModelInitFromTable,
  formRulesInitFromTable
} from "@/utils/formutils.js";
import {
  trueFalseRenderer
} from "@/utils/tableutils.js";

//meta info
var role = "role";// 表格名称
var columnsAttr = "Columns";// 列
var dataAttr = "Data";// 数据
var selectionAttr = "Selection";// 选中
var dlgVisibleAttr = "DlgVisible";// 对话框
var formAttr = "Form";
var recordAttr = "Record";// 表单模型
var rulesAttr = "Rules";// 表单验证
var curPageAttr = "CurrentPage";// 分页-当前页
var totalNumAttr = "TotalNum";// 分页-总数
var qParamAttr = "QueryParams";// 查询参数

// 角色信息-列
var roleColumns = [{
  prop: "jsbh",
  label: "角色编号",
  hidden: true
}, {
  prop: "jsmc",
  label: "角色名称",
  width: 150,
  rules: [{
    required: true,
    message: "请输入角色名称",
    trigger: "blur"
  }]
}, {
  prop: "jsms",
  label: "角色描述"
}, {
  prop: "sfqy",
  label: "是否启用",
  type: "boolean",
  width: 90,
  outOfSearch: true,
  align: "center",
  headerAlign: "center",
  renderer: trueFalseRenderer
}];

// 角色操作管理信息-模型
var roleToOperation = [{
  prop: "jsbh",
  label: "角色编号"
}, {
  prop: "czbh",
  label: "操作编号"
}];


export default {
  // 使用其他子组件
  components: {
    "table-panel": TablePanel,
    "tree-panel": TreePanel
  },
  methods: {
    onSearching: function(tname, params) {
      var me = this;
      let url = "/static/data/system/role.json";// /sysJsxxb

      if(url !== "") {
        me[tname+qParamAttr] = {};
        me[tname+qParamAttr] = params;
        if (params.isAccurate) {
          me[tname+qParamAttr] = params.paramPairs;
        } else {
          me[tname+qParamAttr].keywords = params.query;
        }
        me.getRequest(url, me[tname+qParamAttr]).then(resp => {
            if(resp.status == 200) {
              me[tname+dataAttr] = resp.data;//全查
              // me[tname+totalNumAttr] = resp.data.total;
            }
        });
      }

    },
    onCreate: function(tname) {// 新增
      var me = this;
      me[tname+recordAttr] = formModelInitFromTable(me[tname+columnsAttr]);
      me[tname+recordAttr].sfqy = "1";// 创建时，有效否是选中的

      me[tname+dlgVisibleAttr] = true;
    },
    onEdit: function(tname, row) {// 编辑
      var me = this;
      me[tname+recordAttr]= row;
      me[tname+dlgVisibleAttr] = true;
    },
    onDelete: function(tname, row) {// 删除 
      var me = this;
      me.$confirm("确定删除这条记录吗?", "提示", {
        type: "warning"
      }).then(() => {
        me.deleteRequest(`/sysJsxxb/${row.jsbh}`).then((resp)=>{
          if(resp.status == 200) {
            me.$message.success("删除成功!");
            me.onSearching(role,{});// 重新加载表格数据
          }else{
            me.$message.error("删除失败！");
          }
        });
      }).catch(() => {});
    },
    onExport: function(tname, params) {// 导出
      var me = this;
      me.$message({
        type: "info",
        message: "发送导出请求，返回下载路径"
      });
    },
    onSelectionChange: function(tname, params) {// 角色-选中改变
      var me = this;
      // 按照角色编号，查询对应的选中权限节点数组
      // 缓存记录
      me[tname+selectionAttr] = params;
      // 先清空上一次选中的
      me.$refs.authorityTree.clearChecked();
      // /static/data/system/roleselected.json
      me.getRequest("/sysCzxxb/czbhs",{
        jsbh:params.jsbh
      }).then((resp)=>{
        if(resp.status == 200){
          // 传入一个选中的数组
          me.$refs.authorityTree.setCheckedKeys(me.arrUtil.transObjArrToSimpleArr(resp.data,"czbh"));
        }else {
          me.$message({
            message:"服务器读取错误！",
            type:"error"
          });
        }
      });

    },
    onCheckChange:function() {// 权限树-选中改变

    },
    onSave:function() {// 保存权限分配
      let me = this;
      let nodes = me.$refs.authorityTree.getCheckedNodes(true);

      // TODO 把拿到的叶子节点，也就是操作编号列表，发送给后台保存
      // 发送[role+selectionAttr]的编号和一组node
      let role = me.roleSelection;

      // 验证
      if(!role || !role.jsbh || role.jsbh == ""){
        me.$message.warning("请选择一个角色！");
        return;
      }
      if(nodes.length < 1){
        me.$message.warning("请选择至少一个操作！");
        return;
      }
      
      let czArr = me.arrUtil.transObjArrToSimpleArr(nodes, "id");
      
      // static/data/testSuc.json
      me.postRequest("/sysCzxxb/jsczgl",{
        jsbh:role.jsbh,
        czbhs:czArr.toString()
      }).then((resp)=>{
        if (resp.status == 200) {
          me.$message.success(resp.data.msg);
        } else{
          me.$message.error("服务器发生错误，代码：" + resp.status);
        }
      });
    },
    onConfirm:function(tname, params){// 对话框-确认
      var me = this;
      // 验证信息
      var ret;
      me.$refs[tname + formAttr].validate((result, what)=>{
        ret = result;
      });
      if(!ret){
        me.$message({
          message: "表单信息有误",
          type: "error"
        });
        return;
      }
      // 发送请求 /static/data/testSuc.json
      me.postRequest("/sysJsxxb",me[tname+recordAttr]).then((resp)=>{
        if (resp.status == 200) {
          me.$message.success("提交成功！");
          //最后，隐藏对话框
          me[tname + dlgVisibleAttr] = false;
          me.onSearching(role,{});// 重新加载表格数据
        } else{
          me.$message.error("服务器发生错误，代码：" + resp.status);
        }
      });
    },
    onPageChange:function(tname, page){// 分页改变
      var me = this;
      let url = "/sysJsxxb";

      if(url !== ""){
        me[tname+curPageAttr] = page;
        me[tname+qParamAttr]["page"] = page;
        me.getRequest(url, me[tname+qParamAttr]).then(resp => {
            if(resp.status == 200) {
              me[tname+dataAttr] = resp.data.results;
              me[tname+totalNumAttr] = resp.data.total;
            }
        });
      }

    }
  },
  data() {
    return {
      authorities: {
        create:true,
        delete:true,
        edit:true,
        search:true
      },// 权限控制
      [role+columnsAttr]: roleColumns,// 角色表格-列
      [role+dataAttr]: [],// 角色表格的数据
      authorityTree:[],// 权限树
      [role+selectionAttr]:{},// 当前选中的角色
      [role+dlgVisibleAttr]:false,// 对话框是否可见
      [role+recordAttr]:{},// 表单模型
      [role+rulesAttr]:{},// 表单验证
      [role+curPageAttr]:1,
      [role+totalNumAttr]:0,
      [role+qParamAttr]:{},
      pageSize:20// 每页数量
    };
  },
  created: function() {
    var me = this;
    // 一开始就加载权限树 /static/data/system/roleTree.json
    me.getRequest("/sysCzxxb/menu").then((resp)=>{
      if(resp.status==200 && resp.data.success) {
        me.authorityTree = resp.data.routes;//me.transRoutesToNodes(resp.data.routes);
      }else{
        me.$message.error("服务器发生错误，代码：" + resp.status);
      }
    }); 

    // 添加权限控制
    // me.authorities = me.$route.meta.authorities;

    // 表单模型初始化
    me[role+recordAttr] = formModelInitFromTable(me[role+columnsAttr]);
    // 表单验证初始化
    me[role+rulesAttr] = formRulesInitFromTable(me[role+columnsAttr]);

    me.onSearching(role,{});
  }
}
</script>
<style lang="scss">

.components-system-role{
  height:100%;
}

</style>
